using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Drawing;

namespace GraphAlgsPresentation.Core
{
    /// <summary>
    /// Drawing with blind effect
    /// </summary>
    class BlindDrawing : IEffect
    {
        Timer timer = new Timer();
        GraphPlotter gplotter;
        int alpha;

        /// <summary>
        /// Initializes a new instance of the <see cref="BlindDrawing"/> class.
        /// </summary>
        public BlindDrawing()
        {
            timer.Tick += new EventHandler(timer_Tick);
        }

        /// <summary>
        /// Handles the Tick event of the timer control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        void timer_Tick(object sender, EventArgs e)
        {
            DoubleBuffer db = gplotter.Buffer;
            alpha = (alpha + 32) % 256;
            if (alpha == 0)
            {
                timer.Stop();
                if (gplotter.Alarm != null)
                    gplotter.Alarm(this, new AlarmEventArgs(string.Empty));
                return;
            }
            db.ResetDoubleBufferBackground();
            Graphics g = db.GetDoubleBufferBackgroundGraphics();
            foreach (LCVertex vertex in gplotter.LayoutContext.Vertices)
                if (vertex.Updated) vertex.DrawAlpha(g, alpha);
            foreach (LCEdge edge in gplotter.LayoutContext.Edges)
                if (edge.Updated) edge.DrawAlpha(g, alpha);
            g.Dispose();
            g = gplotter.CreateGraphics();
            db.DrawImage(g, db.GetDoubleBufferBackgroundBitmap());
            g.Dispose();
        }

        /// <summary>
        /// Draws the specified plotter.
        /// </summary>
        /// <param name="plotter">The plotter.</param>
        public void Draw(GraphPlotter plotter)
        {
            gplotter = plotter;
            DoubleBuffer db = plotter.Buffer;
            if (plotter.LayoutContext == null) return;
            bool stop = true;
            db.ResetBufferBackground();
            Graphics g = db.GetBufferBackgroundGraphics();
            g.Clear(plotter.LayoutContext.BackColor);
            foreach (LCVertex vertex in plotter.LayoutContext.Vertices)
                if (!vertex.Updated) vertex.Draw(g);
                else stop = false;
            foreach (LCEdge edge in plotter.LayoutContext.Edges)
                if (!edge.Updated) edge.Draw(g);
                else stop = false;
            g.Dispose();
            if (stop)
            {
                plotter.Alarm(this, new AlarmEventArgs(string.Empty));
                return;
            }
            alpha = 0;
            timer.Interval = 100;
            timer.Start();
        }
    }
}
